<template>
    <div class="tag-container">
        <el-row :gutter="20">
            <el-col :span="3">
                <div class="orgs-div">
                    <div class="orgs-header">
                        <el-input v-model="orgFilterName" placeholder="输入部门名称" clearable prefix-icon="Search">
                        </el-input>
                    </div>
                    <div class="orgs-container">
                        <el-tree ref="orgsRef" :data="orgsData" :expand-on-click-node="false"
                            :props="{ label: 'name', children: 'children' }" node-key="id" highlight-current
                            default-expand-all @node-click="orgsSelectedhandler" :filter-node-method="filterOrgs">

                        </el-tree>
                    </div>
                </div>
            </el-col>
            <el-col :span="20">
                <!-- 查询表单 -->
                <div class="query-form-container">
                    <el-form :inline="true" :model="queryInputModel" label-width="80px">
                        <el-form-item label="编码:" prop="code">
                            <el-input v-model="queryInputModel.confident.code" placeholder="编码" clearable
                                style="width: 150px"></el-input>
                        </el-form-item>
                        <el-form-item label="名称:" prop="name">
                            <el-input v-model="queryInputModel.confident.name" placeholder="名称" clearable
                                style="width: 150px"></el-input>
                        </el-form-item>

                        <el-form-item label="是否启用:" prop="status">
                            <dictselection v-model="queryInputModel.confident.status" clearable style="width: 150px"
                                classCode="system:Status" :dictData="statsDic">
                            </dictselection>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="refreshHandler">查询</el-button>
                            <el-button icon="Delete" @click="resetQueryInputHandler">清空</el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <!-- 数据表格 -->
                <div class="table-container">
                    <!-- 操作按钮 -->
                    <div class="action-button-container">
                        <el-row :gutter="5">
                            <el-col :span="1.5">
                                <el-button size="small" icon="Refresh" type="primary" plain
                                    @click="refreshHandler">刷新</el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button size="small" icon="Plus" type="primary" plain
                                    @click="addHandler">新增</el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button size="small" icon="Download" type="warning" plain>导出</el-button>
                            </el-col>
                        </el-row>
                    </div>

                    <el-table :data="userPaggerData.data" row-key="id" border style="width: 100%">
                        <!-- 自动生成序号列 -->
                        <el-table-column type="index" label="" width="30px" align="center"></el-table-column>
                        <el-table-column prop="code" label="编码" width="80px"
                            :show-overflow-tooltip="true"></el-table-column>
                        <el-table-column prop="name" label="名称" width="100px"
                            :show-overflow-tooltip="true"></el-table-column>
                        <!-- <el-table-column prop="nickName" label="昵称" width="100px"
                            :show-overflow-tooltip="true"></el-table-column> -->
                        <el-table-column prop="mainOrgId" label="主部门" width="100px" :show-overflow-tooltip="true">
                            <template #default="scope">
                                {{ scope.row.mainOrg ? scope.row.mainOrg.name : '' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="mainPostId" label="主岗位" width="100px" :show-overflow-tooltip="true">
                            <template #default="scope">
                                {{ scope.row.mainPost ? scope.row.mainPost.name : '' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="email" label="邮箱" width="150px"
                            :show-overflow-tooltip="true"></el-table-column>
                        <el-table-column prop="phone" label="电话" width="100px"
                            :show-overflow-tooltip="true"></el-table-column>
                        <el-table-column prop="status" label="状态" width="80" :show-overflow-tooltip="true">
                            <template #default="{ row }">
                                <el-switch v-model="row.status" :active-value="1" :inactive-value="0"
                                    @change="setStatus(row)"></el-switch>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="createdAt" label="创建时间" width="180" :show-overflow-tooltip="true"></el-table-column> -->
                        <!-- <el-table-column prop="createdBy" label="创建人" width="120" :show-overflow-tooltip="true"></el-table-column> -->
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button link size="small" icon="Edit" @click="editHandler(scope.row)">编辑</el-button>

                                <el-button link size="small" type="danger" icon="Delete"
                                    @click="deleteHandler(scope.row)">删除</el-button>

                                <el-button link size="small" icon="Menu"
                                    @click="dia_org_open(scope.row)">部门授权</el-button>

                                <el-button link size="small" icon="Menu"
                                    @click="dia_post_open(scope.row)">设置岗位</el-button>

                                <el-button link size="small" icon="Menu"
                                    @click="dia_role_open(scope.row)">设置角色</el-button>

                            </template>
                        </el-table-column>
                    </el-table>

                    <el-pagination size="small" style="margin-top:10px" :total="userPaggerData.pageCount || 0"
                        :page-sizes="[10, 20, 30, 40]" :pager-count="5" :background="true" layout="prev, pager, next"
                        v-model:current-page="queryInputModel.pageIndex" v-model:page-size="queryInputModel.pageSize"
                        @change="loadData">
                    </el-pagination>

                </div>
            </el-col>
        </el-row>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="form.open" :title="form.title" append-to-body center>
            <el-form ref="formRef" :model="form.data" :rules="form.rules" label-width="auto">
                <el-row>
                    <el-col :span="12"> <el-form-item label="编码" prop="code">
                            <el-input v-model="form.data.code"></el-input>
                        </el-form-item></el-col>
                    <el-col :span="12"> <el-form-item label="名称" prop="name">
                            <el-input v-model="form.data.name"></el-input>
                        </el-form-item></el-col>
                </el-row>

                <el-row>
                    <el-col :span="12"> <el-form-item label="主部门" prop="mainOrgId">
                            <el-tree-select v-model="form.data.mainOrgId" :data="orgsData" filterable
                                :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id"
                                placeholder="选择主部门" clearable check-strictly />

                        </el-form-item></el-col>
                    <el-col :span="12"> <el-form-item label="主岗位" prop="mainPostId">
                            <el-select v-model="form.data.mainPostId" placeholder="选择主岗位" filterable clearable>
                                <el-option v-for="sd in postData" :key="sd.id" :label="sd.name"
                                    :value="sd.id"></el-option>
                            </el-select>
                        </el-form-item></el-col>
                </el-row>

                <el-row>
                    <el-col :span="12"> <el-form-item label="昵称" prop="nickName">
                            <el-input v-model="form.data.nickName"></el-input>
                        </el-form-item></el-col>
                    <el-col :span="12"> <el-form-item label="密码" prop="passWord">
                            <el-input v-model="form.data.passWord" type="password"></el-input>
                        </el-form-item></el-col>
                </el-row>

                <el-row>
                    <el-col :span="12"><el-form-item label="邮箱" prop="email">
                            <el-input v-model="form.data.email"></el-input>
                        </el-form-item></el-col>
                    <el-col :span="12"><el-form-item label="电话" prop="phone">
                            <el-input v-model="form.data.phone"></el-input>
                        </el-form-item></el-col>
                </el-row>

                <el-row>
                    <el-col :span="12"><el-form-item label="头像" prop="profilePicture">
                            <el-input v-model="form.data.profilePicture"></el-input>
                        </el-form-item></el-col>
                    <el-col :span="12"> <el-form-item label="状态" prop="status">
                            <dictselection v-model="form.data.status" classCode="system:Status" :dictData="statsDic">
                            </dictselection>
                        </el-form-item></el-col>
                </el-row>

            </el-form>
            <template #footer>
                <el-button @click="form.open = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>


        <!-- 部门授权 -->
        <el-dialog v-model="dia_orgs_openFlag" title="选择部门" width="500px">
            <el-table max-height="400px" ref="orgsTable" :tree-props="{ checkStrictly: true }" :data="orgsData"
                row-key="id" style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="code" label="编号"></el-table-column>
                <el-table-column prop="name" label="名称"></el-table-column>
            </el-table>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dia_org_clear_handler">清除选择</el-button>
                    <el-button @click="dia_orgs_openFlag = false">取消</el-button>
                    <el-button type="primary" @click="dia_org_granthandler">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 岗位授权 -->
        <el-dialog v-model="dia_posts_openFlag" title="岗位" width="500px">
            <el-table max-height="350px" height="350px" ref="postsTable" :data="postData" row-key="id"
                style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="code" label="编号"></el-table-column>
                <el-table-column prop="name" label="名称"></el-table-column>
            </el-table>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dia_post_clear_handler">清除选择</el-button>
                    <el-button @click="dia_posts_openFlag = false">取消</el-button>
                    <el-button type="primary" @click="dia_post_granthandler">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 岗位授权 -->
        <el-dialog v-model="dia_roles_openFlag" title="岗位" width="500px">
            <el-table max-height="350px" height="350px" ref="rolesTable" :data="roleData" row-key="id"
                style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <!-- <el-table-column prop="code" label="编号"></el-table-column> -->
                <el-table-column prop="name" label="角色名称"></el-table-column>
            </el-table>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dia_role_clear_handler">清除选择</el-button>
                    <el-button @click="dia_roles_openFlag = false">取消</el-button>
                    <el-button type="primary" @click="dia_role_granthandler">确定</el-button>
                </span>
            </template>
        </el-dialog>


    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import dictselection from '@/components/DictExtend/DictSelectionWithData.vue';
import msgHelper from '@/util/msgHelper.js'
import userApi from '@/api/system/user.js'
import orgApi from '@/api/system/org.js'
import postApi from '@/api/system/post.js'
import roleApi from "@/api/system/role.js";
import dictApi from "@/api/system/dict.js"


const { proxy } = getCurrentInstance();
const orgsData = ref([]);
const postData = ref([]);
const roleData = ref([]);

const orgsRef = ref('');
const orgsTable = ref('');
const postsTable = ref('');
const rolesTable = ref('');

const userPaggerData = ref({});
const currentUser = ref({});
const queryInputModel = ref(
    {
        pageIndex: 1,
        pageSize: 10,
        confident: {
            code: undefined,
            name: undefined,
            status: null,
            orgid: undefined
        }
    }
); // 查询条件
const statsDic = ref([]);

const form = ref({
    open: false,
    title: '新增',
    data: {
        id: undefined,
        code: '',
        name: '',
        nickName: '',
        passWord: '',
        email: '',
        phone: '',
        profilePicture: '',
        status: 1,
        mainOrgId: undefined,
        mainPostId: undefined
    },
    rules: {
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        passWord: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
        mainOrgId: [{ required: true, message: '请输入主部门', trigger: 'blur' }],
        mainPostId: [{ required: true, message: '请输入主岗位', trigger: 'blur' }],
    },
});

const dia_orgs_openFlag = ref(false);
const dia_posts_openFlag = ref(false);
const dia_roles_openFlag = ref(false);

// 加载数据
const loadData = async () => {
    try {
        var currentData = orgsRef.value.getCurrentNode();
        if (currentData) {
            queryInputModel.value.confident.orgid = currentData.id;
        }
        const res = await userApi.getPagger(queryInputModel.value);
        userPaggerData.value = res.data.data;
    } catch (error) {
        msgHelper.showError('加载数据失败');
    }
};

// 刷新数据
const refreshHandler = () => {
    loadData();
};

// 清空查询条件
const resetQueryInputHandler = () => {
    queryInputModel.value =
    {
        pageIndex: 1,
        pageSize: 10,
        confident: {
            code: undefined,
            name: undefined,
            status: null,
            orgid: undefined
        }
    };
};

// 新增
const addHandler = () => {
    resetForm();
    form.value.title = "新增";
    form.value.open = true;
};

// 重置表单
const resetForm = () => {
    form.value.data = {
        id: undefined,
        code: '',
        name: '',
        nickName: '',
        passWord: '',
        email: '',
        phone: '',
        profilePicture: '',
        status: 1,
    };
};

// 编辑
const editHandler = (row) => {
    resetForm();
    userApi.getByid({ id: row.id, version: row.version }).then(res => {
        if (res.status == 200 && res.data.code == 1) {
            form.value.data = res.data.data;
            form.value.open = true;
            form.value.title = "编辑";
        } else {
            msgHelper.show("获取数据失败" + res.data.msg);
        }
    });
};

// 删除
const deleteHandler = async (row) => {
    try {
        await userApi.del({ id: row.id, version: row.version });
        msgHelper.show('删除成功');
        loadData();
    } catch (error) {
        msgHelper.showError('删除失败');
    }
};

// 提交表单
const submitForm = async () => {
    if (form.value.data.id) {
        await userApi.update(form.value.data);
        msgHelper.show('更新成功');
    } else {
        await userApi.add(form.value.data);
        msgHelper.show('新增成功');
    }
    form.value.open = false;
    loadData();
};

onMounted(async () => {

    const Sres = await dictApi.getDataByCode("System:Status");
    if (Sres.data && Sres.data.data) {
        statsDic.value = Sres.data.data;
    }

    const Ores = await orgApi.getTree({});
    if (Ores.data && Ores.data.data) {
        orgsData.value = Ores.data.data;
    }

    const Pres = await postApi.list({});
    if (Pres.data && Pres.data.data) {
        postData.value = Pres.data.data;
    }

    const Rres = await roleApi.list({});
    if (Rres.data && Rres.data.data) {
        roleData.value = Rres.data.data;
    }

});

const setStatus = async (row) => {
    await userApi
        .setStatus({ id: row.id, status: row.status, version: row.version })
        .then(res => {
            if (res.data.success) {
                msgHelper.show('更新成功');
                loadData();
            }
            else {
                msgHelper.showError('更新失败');
            }
        })
        .catch(error => {
            msgHelper.showError('更新失败');
        });

}
const orgsSelectedhandler = (val) => {

    loadData();

}
const filterOrgs = (value, data) => {
    if (!value) return true;
    return data.name.indexOf(value) !== -1;
}
const orgFilterName = ref("");


watch(orgFilterName, (val) => {
    if (orgsRef.value) {
        orgsRef.value.filter(val);
    }
});

const dia_org_clear_handler = () => {
    orgsTable.value.clearSelection();
}

const dia_post_clear_handler = () => {
    postsTable.value.clearSelection();
}

const dia_role_clear_handler = () => {
    rolesTable.value.clearSelection();
}

const dia_org_granthandler = () => {
    let orgs = orgsTable.value.getSelectionRows();
    let orgids = [];
    if (orgs && orgs.length > 0) {
        orgids = orgs.map(x => x.id);
    }

    var data = {
        userId: currentUser.value.id,
        version: currentUser.value.version,
        orgIds: orgids
    };

    userApi.grantUserOrg(data).then(res => {
        if (res.data.success) {
            msgHelper.show('授权成功');
            dia_orgs_openFlag.value = false;
        }
        else {
            msgHelper.showError('授权失败');
        }
    }).catch(error => {
        msgHelper.showError('授权失败');
    });

}


const dia_role_granthandler = () => {
    let role = rolesTable.value.getSelectionRows();
    let roleIds = [];
    if (role && role.length > 0) {
        roleIds = role.map(x => x.id);
    }

    var data = {
        userId: currentUser.value.id,
        version: currentUser.value.version,
        roleIds: roleIds
    };

    userApi.grantUserRole(data).then(res => {
        if (res.data.success) {
            msgHelper.show('授权成功');
            dia_roles_openFlag.value = false;
        }
        else {
            msgHelper.showError('授权失败');
        }
    }).catch(error => {
        msgHelper.showError('授权失败');
    });

}



const dia_post_granthandler = () => {
    let post = postsTable.value.getSelectionRows();
    let postIds = [];
    if (post && post.length > 0) {
        postIds = post.map(x => x.id);
    }

    var data = {
        userId: currentUser.value.id,
        version: currentUser.value.version,
        postIds: postIds
    };

    userApi.grantUserPost(data).then(res => {
        if (res.data.success) {
            msgHelper.show('授权成功');
            dia_posts_openFlag.value = false;
        }
        else {
            msgHelper.showError('授权失败');
        }
    }).catch(error => {
        msgHelper.showError('授权失败');
    });

}

const dia_org_open = async (row) => {
    currentUser.value = row;

    dia_orgs_openFlag.value = true;

    proxy.$nextTick(async (item) => {
        orgsTable.value.clearSelection();
        var Odata = await userApi.getByid({ id: row.id, version: row.version });
        if (Odata.data && Odata.data.data && Odata.data.data.organizations) {
            Odata.data.data.organizations.forEach(m => {
                const row = findRowById(orgsTable.value.data, m.id);
                if (row) {
                    orgsTable.value.toggleRowSelection(row, true);
                }
            });

        }

    });

}

const findRowById = (data, id) => {
    for (const row of data) {
        if (row.id === id) {
            return row;
        }
        if (row.children && row.children.length > 0) {
            const found = findRowById(row.children, id);
            if (found) {
                return found;
            }
        }
    }
    return null;
};


const dia_post_open = (row) => {

    currentUser.value = row;
    dia_posts_openFlag.value = true;

    proxy.$nextTick(async (item) => {
        postsTable.value.clearSelection();
        var Odata = await userApi.getByid({ id: row.id, version: row.version });
        if (Odata.data && Odata.data.data && Odata.data.data.posts) {
            Odata.data.data.posts.forEach(m => {
                const row = findRowById(postsTable.value.data, m.id);
                if (row) {
                    postsTable.value.toggleRowSelection(row, true);
                }
            });
        }

    });
}


const dia_role_open = (row) => {

    currentUser.value = row;
    dia_roles_openFlag.value = true;

    proxy.$nextTick(async (item) => {
        rolesTable.value.clearSelection();
        var Odata = await userApi.getByid({ id: row.id, version: row.version });
        if (Odata.data && Odata.data.data && Odata.data.data.roles) {
            Odata.data.data.roles.forEach(m => {
                const row = findRowById(rolesTable.value.data, m.id);
                if (row) {
                    rolesTable.value.toggleRowSelection(row, true);
                }
            });
        }
    });
}


</script>

<style scoped>
.orgs-div{
    height: 100%;
    background-color: white !important;
    border-radius: 0%;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.05);
}


</style>